package com.ship.dispatch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.SpBoastPortMessage;
import com.ship.dispatch.bean.boats.*;
import com.ship.dispatch.bean.boats.info.QueryBoatsPortDetailsInfo;
import com.ship.dispatch.bean.boats.info.QueryBoatsPortInfo;
import com.ship.dispatch.bean.boats.info.QueryBoatsPortSisterInfo;
import com.ship.dispatch.bean.boats.info.QueryPortInfo;
import com.ship.dispatch.mapper.BoastPortMessageMapper;
import com.ship.dispatch.mapper.SpBoastPortMessageMapper;
import com.ship.dispatch.model.dto.SpBoastPortMessageDetailDto;
import com.ship.dispatch.model.dto.SpBoastPortMessageShipDetailDto;
import com.ship.dispatch.service.BoastPortMessageService;
import com.ship.dispatch.service.SpInformationService;
import com.ship.dispatch.vo.SpBoastPortMessageDetailVo;
import com.ship.dispatch.vo.SpBoastPortMessageExportVo;
import com.ship.dispatch.vo.SpBoastPortMessageVo;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ship.common.core.domain.URLUtils.decodeURL;

/**
 * <b>BoastPortMessageServiceImpl</b>
 *
 * @description: BoastPortMessageServiceImpl <br>
 * @date: 2024/4/8 09:49 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class BoastPortMessageServiceImpl extends ServiceImpl<BoastPortMessageMapper, SpBoastPortMessage> implements BoastPortMessageService {
    private static final Logger logger = LoggerFactory.getLogger(BoastPortMessageServiceImpl.class);

    @Value("${file_server.host}")
    private String fileServerHost;

    @Autowired
    private SpInformationService spInformationService;

    @Autowired
    private RemoteFileService remoteFileService;

    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    @Override
    public PageInfo<QueryBoatsPortInfo> queryBoatsPortList(QueryBoatsPortRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<QueryBoatsPortInfo> boatsPortList = baseMapper.queryBoatsPortList(rq.getShipNameList(),rq.getImoList(),rq.getPortNameList(),null);
        PageInfo<QueryBoatsPortInfo> pageInfo = new PageInfo<>(boatsPortList);
        if (CollectionUtil.isNotEmpty(rq.getImoList()) || CollectionUtil.isNotEmpty(rq.getShipNameList())){
            if (CollectionUtil.isNotEmpty(boatsPortList) && "1".equals(rq.getSisterStatus()) ){
                //查询姊妹船列表
                List<String> sisterIdList = baseMapper.queryBoatsPortSisterList(boatsPortList.get(0).getShipName(),boatsPortList.get(0).getImo());
                if (CollectionUtil.isNotEmpty(sisterIdList)){
                    List<QueryBoatsPortInfo> sisterBoatsPortList = baseMapper.querySisterBoatsPort(sisterIdList);
                    if (CollectionUtil.isNotEmpty(sisterBoatsPortList)) {
                        boatsPortList.addAll(sisterBoatsPortList);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(boatsPortList)){
            boatsPortList.forEach(item -> {
                //统计挂靠港次数
               List<QueryPortInfo> portList = baseMapper.countPortTotal(item.getShipName(),null,item.getImo());
                if (CollectionUtil.isNotEmpty(portList)){
                    item.setPortOfCallNumber(portList.size());
                    if (portList.size()>=5){
                        item.setPortNameTop1(portList.get(0).getPortNameEn());
                        item.setPortNameTop2(portList.get(1).getPortNameEn());
                        item.setPortNameTop3(portList.get(2).getPortNameEn());
                        item.setPortNameTop4(portList.get(3).getPortNameEn());
                        item.setPortNameTop5(portList.get(4).getPortNameEn());
                    }else {
                        for (int i = 1; i <= portList.size(); i++) {
                            if (i==1){
                                item.setPortNameTop1(portList.get(0).getPortNameEn());
                            }else if (i == 2){
                                item.setPortNameTop2(portList.get(1).getPortNameEn());
                            }else if (i == 3){
                                item.setPortNameTop3(portList.get(2).getPortNameEn());
                            }else if (i == 4){
                                item.setPortNameTop4(portList.get(3).getPortNameEn());
                            }else if (i == 5){
                                item.setPortNameTop5(portList.get(4).getPortNameEn());
                            }
                        }
                    }
                }
            });
        }
        pageInfo.setList(boatsPortList);
        return pageInfo;
    }

    @Override
    public QueryBoatsPortDetailsInfo queryBoatsPortByImo(String imo) {
        QueryBoatsPortDetailsInfo boatsPortDetailsInfo = baseMapper.queryBoatsPortByImo(imo);
        if (null != boatsPortDetailsInfo){
            List<QueryPortInfo> portList = baseMapper.countPortTotal(boatsPortDetailsInfo.getShipName(),null,boatsPortDetailsInfo.getImo());
            if (CollectionUtil.isNotEmpty(portList)){
                boatsPortDetailsInfo.setPortOfCallNumber(portList.size());
            }
        }
        return boatsPortDetailsInfo;
    }

    @Override
    public PageInfo<QueryPortInfo> queryBoatsPortDetailsList(QueryBoatsPortDetailsRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<QueryPortInfo> portList = baseMapper.countPortTotal(null,rq.getPortName(),rq.getImo());
        PageInfo<QueryPortInfo> pageInfo = new PageInfo<>(portList);
        return pageInfo;
    }

    @Override
    public List<QueryBoatsPortSisterInfo> queryBoatsPortSisterList(QueryPortSisterRq rq) {
        QueryBoatsBaseRq queryBoatsBaseRq = new QueryBoatsBaseRq();
        queryBoatsBaseRq.setShipName(rq.getShipName());
        List<String> boatsPortSisterList = baseMapper.queryBoatsPortSisterList(rq.getShipName(),rq.getImo());
        if (CollectionUtil.isNotEmpty(boatsPortSisterList)){
            queryBoatsBaseRq.setBoatsPortSisterList(boatsPortSisterList);
            List<QueryBoatsPortSisterInfo> boatsPortSisterInfos =spInformationService.queryBoatsSister(queryBoatsBaseRq);
            return boatsPortSisterInfos;
        }
        return null;
    }

    @Override
    public PageInfo<SpBoastPortMessage> queryBoatsPortHistoryList(QueryBoatsPortHistoryRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        List<SpBoastPortMessage> boatsPortList = baseMapper.queryBoatsPortHistoryList(rq.getPortName(),rq.getImo(),rq.getStartDate(),rq.getEndDate());
        PageInfo<SpBoastPortMessage> pageInfo = new PageInfo<>(boatsPortList);
        return pageInfo;
    }

    @Override
    public List<QueryBoatsPortInfo> exportBoatsPort(QueryBoatsPortRq rq) {
        List<QueryBoatsPortInfo> boatsPortList = baseMapper.queryBoatsPortList(rq.getShipNameList(),rq.getImoList(),rq.getPortNameList(),rq.getSisterStatus());
        if (CollectionUtil.isNotEmpty(boatsPortList)){
            boatsPortList.forEach(item -> {
                //统计挂靠港次数
                List<QueryPortInfo> portList = baseMapper.countPortTotal(item.getShipName(),null,item.getImo());
                if (CollectionUtil.isNotEmpty(portList)){
                    item.setPortOfCallNumber(portList.size());
                    if (portList.size()>=5){
                        item.setPortNameTop1(portList.get(0).getPortNameEn());
                        item.setPortNameTop2(portList.get(1).getPortNameEn());
                        item.setPortNameTop3(portList.get(2).getPortNameEn());
                        item.setPortNameTop4(portList.get(3).getPortNameEn());
                        item.setPortNameTop5(portList.get(4).getPortNameEn());
                    }else {
                        for (int i = 1; i <= portList.size(); i++) {
                            if (i==1){
                                item.setPortNameTop1(portList.get(0).getPortNameEn());
                            }else if (i == 2){
                                item.setPortNameTop2(portList.get(1).getPortNameEn());
                            }else if (i == 3){
                                item.setPortNameTop3(portList.get(2).getPortNameEn());
                            }else if (i == 4){
                                item.setPortNameTop4(portList.get(3).getPortNameEn());
                            }else if (i == 5){
                                item.setPortNameTop5(portList.get(4).getPortNameEn());
                            }
                        }
                    }
                }
            });
        }
        return boatsPortList;
    }

    @Override
    public List<SpBoastPortMessage> exportBoatsPortHistory(QueryBoatsPortHistoryRq rq) {
        List<SpBoastPortMessage> boatsPortList = baseMapper.queryBoatsPortHistoryList(rq.getPortName(),rq.getImo(),rq.getStartDate(),rq.getEndDate());
        return boatsPortList;
    }

    @Override
    public List<SpBoastPortMessageVo> queryBoatsPortPage(List<String> portNameChsList){
        List<SpBoastPortMessageVo> spBoastPortMessageVos = baseMapper.queryBoatsPortPage(portNameChsList);
        return spBoastPortMessageVos;
    }

    @Override
    public List<QueryPortInfo> countShipTotal(String portNameChs){
        List<QueryPortInfo> queryPortInfos = baseMapper.countShipTotal(portNameChs);
        return queryPortInfos;
    }

    @Override
    public SpBoastPortMessageDetailVo getBoastPortMessageDetail(String portNameChs) {
        SpBoastPortMessageDetailVo boastPortMessageDetailVo = baseMapper.getBoastPortMessageDetail(portNameChs);
        if (null != boastPortMessageDetailVo){
            List<QueryPortInfo> portList = baseMapper.countShipTotal(portNameChs);
            if (CollectionUtil.isNotEmpty(portList)){
                boastPortMessageDetailVo.setShipNum(portList.size());
            }
        }
        return boastPortMessageDetailVo;
    }

    @Override
    public PageInfo<SpBoastPortMessage> getBoatsPortHistoryList(SpBoastPortMessageShipDetailDto boastPortMessageShipDetailDto) {
        PageHelper.startPage(boastPortMessageShipDetailDto.getPageNum(),boastPortMessageShipDetailDto.getPageSize());
        List<SpBoastPortMessage> boatsPortList = baseMapper.getBoatsPortHistoryList(boastPortMessageShipDetailDto.getPortNameChs(),boastPortMessageShipDetailDto.getShipName(),boastPortMessageShipDetailDto.getStartDate(),boastPortMessageShipDetailDto.getEndDate());
        PageInfo<SpBoastPortMessage> pageInfo = new PageInfo<>(boatsPortList);
        return pageInfo;
    }

    @Override
    public List<SpBoastPortMessageExportVo> exportBoatsPortHistoryDetailList(SpBoastPortMessageDetailDto boastPortMessageDetailDto){
        List<SpBoastPortMessageExportVo> boastPortMessageExportVos = new ArrayList<>();
        List<SpBoastPortMessage> boatsPortList = baseMapper.getBoatsPortHistoryList(boastPortMessageDetailDto.getPortNameChs(),null,boastPortMessageDetailDto.getStartDate(),boastPortMessageDetailDto.getEndDate());
        if(null != boatsPortList && boatsPortList.size()>0){
            boatsPortList.stream().forEach(b->{
                SpBoastPortMessageExportVo boastPortMessageExportVo = new SpBoastPortMessageExportVo();
                BeanUtils.copyProperties(b,boastPortMessageExportVo);
                boastPortMessageExportVos.add(boastPortMessageExportVo);
            });
        }
        return boastPortMessageExportVos;
    }

    @Override
    public List<QueryPortInfo> exportBoatsPortDetails(QueryBoatsPortDetailsRq rq) {
        List<QueryPortInfo> portList = baseMapper.countPortTotal(null,rq.getPortName(),rq.getImo());
        return portList;
    }

    @Override
    public List<QueryBoatsPortSisterInfo> exportBoatsPortSisterList(QueryPortSisterRq rq) {
        List<String> boatsPortSisterList = baseMapper.queryBoatsPortSisterList(rq.getShipName(),rq.getImo());
        QueryBoatsBaseRq queryBoatsBaseRq = new QueryBoatsBaseRq();
        queryBoatsBaseRq.setShipName(rq.getShipName());
        if (CollectionUtil.isNotEmpty(boatsPortSisterList)){
            queryBoatsBaseRq.setBoatsPortSisterList(boatsPortSisterList);
            List<QueryBoatsPortSisterInfo> boatsPortSisterInfos =spInformationService.exportBoatsPortSisterList(queryBoatsBaseRq);
            return boatsPortSisterInfos;
        }
        return null;
    }

    @Override
    public List<String> queryMessage(String type) {
        if ("shipName".equals(type)){
            return baseMapper.queryMessageByShipName();
        }else if ("imo".equals(type)){
            return baseMapper.queryMessageByImo();
        }else if ("portName".equals(type)){
            return baseMapper.queryMessageByPortName(null);
        }else if ("portCode".equals(type)){
//            return baseMapper.queryMessageByPortCode();
            return null;
        }
        return null;
    }

    @Override
    public List<String> queryPostNameList(String postName) {
        List<String> postNameList = new ArrayList<>();
        List<String> stringList = baseMapper.queryMessageByPortName(postName);
        postNameList.addAll(stringList);
        List<String> receivingStationNameList = baseMapper.queryPostNameList(postName);
        postNameList.addAll(receivingStationNameList);
//        if (StringUtils.isNotEmpty(postName)){
//            postNameList.add(postName);
//            List<String> stringList = baseMapper.queryPostNameList(postName);
//            postNameList.addAll(stringList);
//        }else {
//            List<String> stringList = baseMapper.queryMessageByPortName();
//            postNameList.addAll(stringList);
//            List<String> receivingStationNameList = baseMapper.queryPostNameList(null);
//            postNameList.addAll(receivingStationNameList);
//        }
        return postNameList;
    }

    @Override
    public String queryShipNameByImo(String imo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable","1");
        queryWrapper.eq("imo",imo);
        List<SpBoastPortMessage> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            return list.get(0).getShipName();
        }
        return null;
    }

    @Override
    public List<Map<String,String>> getBoastPortFileMessageDetail(String portNameChs,String type) {
        if (StringUtils.isEmpty(type) || "1".equals(type)){
            List<Map<String,String>> result = baseMapper.getBoastPortFileMessageDetail(portNameChs);
            for (Map<String, String> map : result) {
                String url = map.get("url");
                String decodedUrl = decodeURL(url);
                map.put("url", decodedUrl);
            }
            return result;
        }else if ("2".equals(type)){
            List<Map<String,String>> result = baseMapper.getBoastPortFileList(portNameChs);
            for (Map<String, String> map : result) {
                String url = map.get("url");
                String decodedUrl = decodeURL(url);
                map.put("url", decodedUrl);
            }
            return result;
        }
        return null;
    }

    @Override
    public String upload(MultipartFile file, String portNameChs,String type) {

        R<SysFile> result1 = remoteFileService.upload(file);
        if(result1.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String result = result1.getData().getHttpsUrl();;
//        try {
//            InputStreamResource isr = new InputStreamResource(file.getInputStream(),
//                    file.getOriginalFilename());
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            //params.put("path", "86501729");
//            params.put("output", "json");
//            /*params.put("auth_token", "123");*/
//            String resp = HttpRequest.post(fileServerHost + FILE_UPLOAD_PATH).form(params).timeout(-1).execute().body();
//            //String resp = HttpUtil.post(fileServerHost + FILE_UPLOAD_PATH, params);
//            JSONObject re = JSONObject.parseObject(resp);
//            if(!re.getString("retcode").equals("0")){
//                throw new BusException(re.getString("retmsg"), BaseResultCode.GENERAL_ERROR);
//            }
//            result = re.getString("domain") + re.getString("path");

//        } catch (Exception e) {
//            throw new BusException("文件服务器连接失败",BaseResultCode.GENERAL_ERROR);
//        }
        Snowflake snowflake = new Snowflake(1, 1);
        String id = String.valueOf(snowflake.nextId());
        if (StringUtils.isEmpty(type) || "1".equals(type)) {
            baseMapper.upFile(id, result, portNameChs);
        }else if ("2".equals(type)){
            baseMapper.addPortFileUrl(id,result,portNameChs);
        }
        return id;
    }

    @Override
    public String delBoatsPortFile(Long id) {
        List<String> file = baseMapper.getBoatsPortFileByID(id);
        if (!file.isEmpty()){
            baseMapper.delBoatsPortFile(id);
            return "删除成功";
        }
        return "删除失败，该文件不存在";
    }

    @Override
    public String getUrl(String id) {
        String url = baseMapper.getUrlByPortNameChs(id);
        return url;
    }

}
